import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
import cookie from './cookie';

type ResponseData<T = unknown> = {
  Code: number,
  data: T
  Message: string
}

class XhrRequest {
  instance: AxiosInstance

  baseConfig: AxiosRequestConfig = { baseURL: `${import.meta.env.MODE === 'development' ? '' : import.meta.env.VITE_APP_URL}/Api`, timeout: 60000 }

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig, config));

    this.instance.interceptors.request.use(
      (configRequest: AxiosRequestConfig) => {
        if (configRequest && configRequest.headers) {
          configRequest.headers.token = cookie.getToken();
        }
        return configRequest;
      },
      (error) => Promise.reject(error),
    );

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        if (res.data.code === 1) {
          return Promise.resolve(res);
        }
        if (res.data.code === 400001) {
          cookie.removeToken();

          if (!window.location.pathname.includes('/login')) {
            router.replace(
              '/login',
            );
          }
          return Promise.reject(new Error(res.data.message));
        }

        ElMessage.error(res.data.message);
        return Promise.reject(res.data.message || 'error');
      },
    );
  }

  public request<T>(config: AxiosRequestConfig) {
    return this.instance.request<ResponseData<T>>(config);
  }

}
const xhr = new XhrRequest({});

export default xhr;
